package org.lc.solon.cmd.util;

import java.util.function.Supplier;

/**
 * 懒加载
 *
 * @param <T> 类型
 */
public class Lazy<T> {
    private volatile Supplier<T> supplier;

    private T data;

    public Lazy(Supplier<T> supplier) {
        if (supplier == null) {
            throw new NullPointerException("supplier should not be null");
        }
        this.supplier = supplier;
    }

    public T get() {
        if (supplier != null) {
            synchronized (this) {
                if (supplier != null) {
                    data = supplier.get();
                    supplier = null;
                }
            }
        }
        return data;
    }
}
